<?php

namespace app\api\Service;

use app\common\library\Auth;
use app\common\model\Area;
use think\Config;
use think\Db;

class WithdrawalService
{
    //提现信息
    public static function getIndex($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $money = $auth->money;
        $deposit = $auth->deposit;
        $wechat = \app\admin\model\UserWithdrawalAccount::where(['user_id'=>$user_id,'type'=>'1'])->field('id,account')->find();
        $alipay = \app\admin\model\UserWithdrawalAccount::where(['user_id'=>$user_id,'type'=>'2'])->field('id,account')->find();
        $bank = \app\admin\model\UserWithdrawalAccount::where(['user_id'=>$user_id,'type'=>'3'])->field('id,account')->find();
        if(!$wechat) $wechat = '';
        if(!$alipay) $alipay = '';
        if(!$bank) $bank = '';

        return ['code' =>1,'msg'=>'查询成功','data'=>['money'=>$money,'deposit'=>$deposit,'wechat'=>$wechat,'alipay'=>$alipay,'bank'=>$bank]];

    }

    //提现信息
    public static function addAccount($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $type = $data['type'];
        $name = $data['name'];
        $account = $data['account'];
        $qrcode = $data['qrcode'];
        $cardholder = $data['cardholder'];
        $mobile = $data['mobile'];

        if(!$type) return ['code'=>0,'msg'=>'请选择提现方式','data'=>''];
        if(($type == 1 || $type == 2) && !$name) return ['code'=>0,'msg'=>'请输入账户名称','data'=>''];
        if($type == 3 && !$name) return ['code'=>0,'msg'=>'请输入银行类型','data'=>''];
        if(($type == 1 || $type == 2) && !$account) return ['code'=>0,'msg'=>'请输入账户','data'=>''];
        if($type == 3 && !$account) return ['code'=>0,'msg'=>'请输入卡号','data'=>''];
        if($type == 3 && !$cardholder) return ['code'=>0,'msg'=>'请输入持卡人','data'=>''];
        if($type == 3 && !$mobile) return ['code'=>0,'msg'=>'请输入手机号','data'=>''];
        if(($type == 1 || $type == 2) && !$qrcode) return ['code'=>0,'msg'=>'请上传二维码','data'=>''];

        $account_data = [
            'user_id' => $user_id,
            'type' => $type,
            'name' => $name,
            'account' => $account,
            'qrcode' => $qrcode,
            'cardholder' => $cardholder,
            'mobile' => $mobile
        ];

        // 开始事务处理
        Db::startTrans();
        try{
            $isExist = \app\admin\model\UserWithdrawalAccount::where(['user_id'=>$user_id,'type'=>$type])->find();
            if($isExist){
                $res = $isExist->save($account_data);
            }else{
                $res = \app\admin\model\UserWithdrawalAccount::create($account_data);
            }

            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }

    }

    // 申请提现
    public static function apply($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $user_money = $auth->money;
        $ids = $data['ids'];
        // $id = $data['id'];

        $ids = explode(',',$ids);
        $amount = 0;
        foreach($ids as $v){
            $money = \app\common\model\MoneyLog::where(['id'=>$v,'user_id'=>$user_id,'is_withdraw'=>0])->value('money');
            $amount += $money;
        }
        if($amount > $user_money) return ['code'=>0,'msg'=>'账户余额不足','data'=>''];
        // $account = \app\admin\model\UserWithdrawalAccount::where(['id'=>$id])->find();
        // if(!$account) return ['code'=>0,'msg'=>'数据不存在','data'=>''];
        $isExist = \app\admin\model\UserWithdrawalApply::where(['user_id'=>$user_id,'status'=>0])->find();
        if($isExist) return ['code'=>0,'msg'=>'存在待审核的提现申请，不要重复提交','data'=>''];

        // 开始事务处理
        Db::startTrans();
        try{
            
            // return $ids;

            foreach($ids as $log_id){
                $order_id = \app\common\model\MoneyLog::where(['id'=>$log_id,'user_id'=>$user_id, 'is_withdraw'=>0])->value('order_id');
                $money = \app\common\model\MoneyLog::where(['id'=>$log_id,'user_id'=>$user_id, 'is_withdraw'=>0])->value('money');
                
                if($order_id){
                    $account_data = [
                        'user_id' => $user_id,
                        'money' => $money,
                        // 'type' => $account['type'],
                        // 'name' => $account['name'],
                        // 'account' => $account['account'],
                        // 'qrcode' => $account['qrcode'],
                        // 'cardholder' => $account['cardholder'],
                        // 'mobile' => $account['mobile'],
                        'order_id' => $order_id,
                    ];
                    // return $account_data;
                    \app\admin\model\UserWithdrawalApply::create($account_data);
                }
            }
            Db::commit();
            // 成功时返回成功信息
            return ['code'=>1,'msg'=>'操作成功','data'=>''];
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>'1'];
        }

    }

    // 解冻押金
    public static function unfreeze($data)
    {
        $auth = Auth::instance();
        $user_id = $auth->id;
        $user_deposit = $auth->deposit;
        $id = $data['id'];

        $account = \app\admin\model\UserWithdrawalAccount::where(['id'=>$id])->find();
        if(!$account) return ['code'=>0,'msg'=>'数据不存在','data'=>''];

        // 注销账号
        $user = \app\admin\model\User::where(['id'=>$user_id])->field('pid,group_id,nickname,mobile,avatar,money,score,deposit')->find();
        \app\admin\model\User::where(['id'=>$user_id])->delete();
        unset($user['prevtime_text']);
        unset($user['logintime_text']);
        unset($user['jointime_text']);
        $params = [
            'pid'   => $user['pid'],
            'group_id'   => $user['group_id'],
            'nickname'   => $user['nickname'],
            'mobile'   => $user['mobile'],
            'avatar'   => $user['avatar'],
            'money'   => $user['money'],
            'score'   => $user['score'],
            'deposit'   => $user['deposit'],
        ];

        // 开始事务处理
        Db::startTrans();
        try{
//            return $params;
            $res = \app\admin\model\UserLogoff::create($params);

            $account_data = [
                'user_id' => $res['id'],
                'money' => $user_deposit,
                'type' => $account['type'],
                'name' => $account['name'],
                'account' => $account['account'],
                'qrcode' => $account['qrcode'],
                'cardholder' => $account['cardholder'],
                'mobile' => $account['mobile']
            ];

            $ret = \app\admin\model\UserUnfreeze::create($account_data);


            // 提交事务
            Db::commit();
            // 判断订单更新是否成功
            if($res && $ret){
                // 成功时返回成功信息
                return ['code'=>1,'msg'=>'操作成功','data'=>''];

            }else{
                // 失败时返回失败信息
                return ['code'=>0,'msg'=>'操作失败','data'=>''];
            }
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 异常时返回异常信息
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    // 提现明细
    public static function logList($data)
    {
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        // 设置每页显示的订单数量，默认为10条
        $limit = isset($data['limit']) && $data['limit'] ? $data['limit'] : 10;

        $list = \app\admin\model\UserWithdrawalApply::where(['user_id'=>$user_id])->field('type,money,createtime,status')->paginate($limit)
            ->each(function
            ($row){
                $row['createtime_text'] = date('Y-m-d H:i:s',$row['createtime']);
            });
        return ['code'=>1,'message'=>'查询成功','data'=>$list];
    }

    // 可提现列表
    public static function getList($data)
    {
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        // 设置每页显示的订单数量，默认为10条
        $limit = isset($data['limit']) && $data['limit'] ? $data['limit'] : 10;

        $list = \app\common\model\MoneyLog::where(['user_id'=>$user_id,'is_withdraw'=>0,'order_id'=>['<>',0]])->field
        ('id,money,createtime,order_id')->paginate($limit)->each(function ($row){
                $row['createtime_text'] = date('Y-m-d H:i:s',$row['createtime']);
                $row['order_no'] = \app\admin\model\Order::where(['id'=>$row['order_id']])->value('order_no');
                unset($row['order_id']);
                unset($row['createtime']);
            });
        return ['code'=>1,'message'=>'查询成功','data'=>$list];
    }
    
    // 可确认列表
    public static function getConfirmList($data)
    {
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        // 设置每页显示的订单数量，默认为10条
        $limit = isset($data['limit']) && $data['limit'] ? $data['limit'] : 10;

        $list = \app\admin\model\UserWithdrawalApply::where(['user_id'=>$user_id,'status'=>1,'package_info'=>['<>',' ']])->field
        ('id,package_info,money,createtime,order_id')->order('createtime desc')->paginate($limit)->each(function ($row){
                $row['createtime_text'] = date('Y-m-d H:i:s',$row['createtime']);
                $row['order_no'] = \app\admin\model\Order::where(['id'=>$row['order_id']])->value('order_no');
                $row['mchid'] = '1709316142';
                $row['appid'] = 'wxa8e0ec7b7f70bdc7';
                unset($row['order_id']);
                unset($row['createtime']);
            });
        return ['code'=>1,'message'=>'查询成功','data'=>$list];
    }
    
    // 确认收款
    public static function payee($data)
    {
        // 实例化认证类以获取当前用户信息
        $auth = Auth::instance();
        // 获取当前用户ID
        $user_id = $auth->id;
        
        $id = $data['id'];
        if(!$id) return ['code'=>0,'message'=>'参数无效'];

        \app\admin\model\UserWithdrawalApply::where(['id'=>$id])->update(['status'=>3]);
        return ['code'=>1,'message'=>'操作成功'];
    }


}